const Base = require("./base");
module.exports = class ProductService extends Base {
  classify(condition = []) {
    const expr = ["status>0", ...condition];
    let sql = `SELECT * FROM product_classify WHERE ${expr.join(" AND ")}`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0]);
  }

  // 根据产品分类id查询并进行类型分组
  _list(pro_id, inGroup = []) {
    let expr = `pro_id=${pro_id}`;
    if (inGroup.length) {
      expr = `pro_id IN(${inGroup.join(",")})`;
    }
    // sort=0,sort 对大于0的数组进行排序
    let sql = `SELECT * FROM product WHERE ${expr} AND status>0 ORDER BY sort=0,sort DESC`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => {
        return res[0];
      });
  }
  list(condition, version) {
    return this.classify(condition).then(async (res) => {
      const dict = {};
      for (let i = 0; i < res.length; i++) {
        const item = res[i];
        if (item.fid) {
          if (dict[item.fid]) {
            dict[item.fid].push(item.id);
          } else {
            dict[item.fid] = [item.fid, item.id];
          }
        }
      }
      for (let i = 0; i < res.length; i++) {
        const item = res[i];
        const list = await this._list(item.id, dict[item.id]);
        list.forEach((listItem) => {
          if (version < "1.0.5") {
            const cdn = this.config.cdn;
            if (listItem.src && listItem.src.indexOf("assets/") < 0) {
              listItem.src = cdn + listItem.src;
            }
            if (listItem.thumb && listItem.thumb.indexOf("assets/") < 0) {
              listItem.thumb = cdn + listItem.thumb;
            }
          }
          let key = "children";

          let groupType = listItem.type;
          if (version < "1.0.5" && item.type === "exclusive") {
            groupType = "exclusive";
          }
          if (groupType) {
            key = `${groupType}s`;
            delete listItem.type;
          }
          if (item[key]) {
            item[key].push(listItem);
          } else {
            item[key] = [listItem];
          }
        });
      }
      return res;
    });
  }

  getUserBackgroundList(params) {
    const { uid, size = 10, page = 1 } = params;
    let expr = `uid='${uid}' AND status>0`;
    const sel =
      "`id`,`pro_id`,`type`,`name`,`describe`,`thumb`,`src`,`url`,`deep`";
    let sql = `SELECT COUNT(id) as total FROM product WHERE ${expr};
    SELECT ${sel} FROM product WHERE ${expr} ORDER BY sort=0,sort LIMIT ${
      (page - 1) * size
    },${size};`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => {
        const p = res[0][0][0] || {};
        return {
          pages: {
            ...p,
            size,
            page,
          },
          list: res[0][1] || [],
        };
      });
  }

  /**
   * @function 用户上传背景图片
   */
  uploadUserBackground(params) {
    const { keys, replacements, values } = this.installParams(params);
    return this.app.mysql
      .use("foindia")
      .query(`INSERT INTO product(${keys}) VALUES(${values})`, {
        replacements,
      })
      .then((res) => ({
        id: res[0],
      }));
  }
  putUserBackground(params) {
    const { id } = params;
    delete params.id;
    delete params.uid;
    const { replacements, values } = this.installParams(params, 2);
    let sql = `UPDATE product SET ${values} WHERE id="${id}"`;
    return this.app.mysql
      .use("foindia")
      .query(sql, {
        replacements,
      })
      .then((res) => res[0])
      .then((res) => res.changedRows);
  }
};
